package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    /*
     *  分页查询菜品
     *
     * */

    @GetMapping("/page")
    public R<Page<Category>> findAll(@RequestParam(required = false, defaultValue = "1") int page,
                                     @RequestParam(required = false, defaultValue = "10") int pageSize, String name) {

        log.info("查询的菜品 page={}", page);
        Page<Category> pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //查询
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }


    /*
     *       新增菜品
     *
     * */
    @PostMapping
    public R addCategory(@RequestBody Category category) {
        log.info("新增菜品分类{}", category);
        categoryService.save(category);
        return R.success();
    }


    /*
     * 查询
     *
     *
     * */

    @GetMapping("/{id}")
    public R<Category> getById(@PathVariable Long id) {

        Category category = categoryService.getById(id);
        if (category != null) {
            return R.success(category);
        }
        return R.error("没有查询到");
    }

    /*
     * 修改更新
     *
     * */

    @PutMapping
    public R update(@RequestBody Category category) {
        log.info("修改分类数据{}", category);
        categoryService.updateById(category);
        return R.success(category);
    }

    /*
     * 删除
     *
     * */

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Long id) {
        log.info("删除分类数据,id为{}", id);
        categoryService.remove(id);
        return R.success();
    }



    /*
     *   根据条件查询分类数据
     * */

    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        //条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper();
        //添加条件
        wrapper.eq(category.getType() != null, Category::getType, category.getType());
        //添加排序条件
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }

}
